package pers.qianyu.month_202012.date_20201202;

/**
 * 剑指 Offer 51. 数组中的逆序对
 * https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof/
 *
 * @author mizzle rain
 * @date 2020-12-02 21:52
 */
public class ReversePairs {
    public int reversePairs(int[] arr) {
        int[] temp = new int[arr.length];
        return solve(arr, 0, arr.length - 1, temp);
    }

    private int solve(int[] arr, int left, int right, int[] temp) {
        if (left >= right) {
            return 0;
        }
        // 分
        int mid = left + ((right - left) >> 1);
        int leftPart = solve(arr, left, mid, temp);
        int rightPart = solve(arr, mid + 1, right, temp);
        int cur = 0;
        // 合并数组
        int p1 = left, p2 = mid + 1, k = 0;
        while (p1 <= mid && p2 <= right) {
            if (arr[p1] > arr[p2]) {
                // 出现逆序对
                cur += mid - p1 + 1;
                temp[k++] = arr[p2++];
            } else {
                temp[k++] = arr[p1++];
            }
        }
        while (p1 <= mid) {
            temp[k++] = arr[p1++];
        }
        while (p2 <= right) {
            temp[k++] = arr[p2++];
        }
        // 将辅助数组中的数写回原数组
        k = 0;
        for (int i = left; i <= right; i++) {
            arr[i] = temp[k++];
        }
        return leftPart + rightPart + cur;
    }

    public static void main(String[] args) {
        int[] arr = {7, 5, 6, 4};
        int result = new ReversePairs().reversePairs(arr);
        System.out.println("result = " + result);
    }
}
